<?php

include 'parseInput.php';

function get_answer_from_db($tags_from_user) {
	
	$dbhost = "localhost";
	$dbuser = "root";
	$dbpass = "";
	$dbname = "fei_hackathon";

	$tags_array = explode(',', $tags_from_user);
	$greatest_value = 0.0;
	$id_to_return = "";
	$final_result ="";
	
	
	$con_db=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die ('Error connecting with the server');
	
	// Check connection
	if (mysqli_connect_errno()) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}


	//Build SELECT Query
	$select_query = "SELECT * FROM answer WHERE";
	
	foreach ($tags_array as $value) {
		$select_query = $select_query." Tags Like '%$value%' AND";
	}
	
	//Remove extra " AND"
	$select_query = substr($select_query,0,strlen($select_query) - 4);	
	
	$result = mysqli_query($con_db,$select_query);
	
	if(mysqli_num_rows($result)==0){
		$result = mysqli_query($con_db,"SELECT response FROM responseBlank ORDER BY rand() LIMIT 1;");
		$final_result = mysqli_fetch_array($result);
		$final_result = $final_result[0];
	}
	
	else{
			//check each match for the accuracy of the match
		while($row = mysqli_fetch_array($result)) {
				$no_of_tags = $row['No_of_Tags'];
				$no_of_tags = (float)(count($tags_array) / $no_of_tags);
				if($no_of_tags > $greatest_value) {
					$greatest_value = $no_of_tags;
					$id_to_return = $row['Answer_ID'];
				}
		}
		
		$result = mysqli_query($con_db,"SELECT Answer FROM answer WHERE Answer_ID = $id_to_return");
		$final_result = mysqli_fetch_array($result);
		$final_result = $final_result[0];
		
	}
	mysqli_close($con_db);
	
	return $final_result;
}

if (isset($_POST['submit'])) {
	file_put_contents('./text_files/conversation_history.txt', '');
}
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Ask Fei</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Le styles -->
    <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
    <link href="bootstrap/css/bootstrap-responsive.css" rel="stylesheet">
	<link href="main.css" rel="stylesheet">
	<link href='http://fonts.googleapis.com/css?family=Lato:300,400,900,300italic,400italic,900italic' rel='stylesheet' type='text/css'>
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="../assets/js/html5shiv.js"></script>
    <![endif]-->

    <!-- Fav and touch icons -->
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
      <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
                    <link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
                                   <link rel="shortcut icon" href="../assets/ico/favicon.png">
    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
	</script>
	<script>
	    $(document).ready(function(){
		    $('textarea[name=question]').click(function(){
			    $(".fei").css("background-image","url(images/FEI_THINKING.gif)");
			});
	    }); 
	</script>	                     
  </head>

  <body>
	<div class = "page">
		<div id="header">
			<h1><span style="font-weight:400">TALKTO</span><span style="font-weight:900"><b>FEI</b></span></h1>
		</div>

		<div id="content">
			<div id = "column-1">
				<div id = "row-1">
					<div class = "fei">
					</div>
					<div class = "bubble">
					<p id="answer">
					<?php
						$question;
						$answer;
						if (isset($_GET['submit'])) {
							$question = $_GET['question'];
							$question = strtolower($question);
							$question = remove_punctuations($question);
							$question = trim(remove_unnecessary_words($question));
							if (strcmp($question, 'i m bored') == 0 || strcmp($question, 'im bored') == 0) {
								header ("Location: CIEgag.php?idNumber=1");
							}
							if (strcmp($question, 'run rb') == 0 || strcmp($question, 'run reviewboard') == 0) {
								header ("Location: http://reviewboard/");
							}
							if (strcmp($question, 'run rpd') == 0 || strcmp($question, 'check rpd') == 0) {
								header ("Location: http://rpd/");
							}
							if (strcmp($question, 'run opengrok') == 0 || strcmp($question, 'check opengrok') == 0) {
								header ("Location: http://opengrok/");
							}
							if (strcmp($question, 'run hr') == 0 || strcmp($question, 'check hr') == 0) {
								header ("Location: http://hr/");
							}
							if (strcmp($question, 'run twiki') == 0 || strcmp($question, 'check twiki') == 0) {
								header ("Location: http://infonet/");
							}
							$tag_list = parse_input($question);
							$answer = get_answer_from_db($tag_list);
							echo $answer;
							
							# update conversation history text file
							file_put_contents('./text_files/conversation_history.txt', 'You:' . PHP_EOL . $question . PHP_EOL . 'Fei:' . PHP_EOL . $answer . PHP_EOL, FILE_APPEND);
						}
					?></p>
					</div>
				</div>
				<div id = "row-2">
					<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
						<textarea name="question" class="form-control" rows="6" placeholder="Enter question here"></textarea>
						<input name="submit" type="submit" class="btn btn-primary" value="ASK!"/>
					</form>
				</div>
			</div>
			<div id = "column-2">
				<span class="label label-primary">Conversations</span>
				<div id="conv_hist" class="form-control text-convo">
					<?php 
						$file = fopen('./text_files/conversation_history.txt', 'r');
						while (!feof($file)) {
					?>					
						<div class="conv_hist_ques"><p><?php echo fgets($file);?><br><span style="font-weight: normal"><?php echo fgets($file);?></span></p></div>
						<div class="conv_hist_answ"><p><?php echo fgets($file);?><br><span style="font-weight: normal"><?php echo fgets($file);?></span></p></div>
					<?php
						};
						fclose($file);
					?>
				</div>
				<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
					<input name="submit" type="submit" class="btn btn-secondary" value="CLEAR"/>
				</form>
			</div>
		</div>

		<div id="footer">
			<center><p class="text-danger">COPYRIGHT &#169; HACKATHON 2014. FEI BY TEAM 8D. ALL RIGHTS RESERVED.<br>
			<a href="https://www.facebook.com/VirgeofDeath12">kbienes</a> . 
			<a href="https://www.facebook.com/laraangelique.igcasan">ligcasan</a> . 
			<a href="https://www.facebook.com/maronavenue">mmontano</a> . 
			<a href="https://www.facebook.com/martmed20">mmedrano</a> . 
			<a href="https://www.facebook.com/nicole.tan.98284">nitan</a></p></center>
		</div>
	</div>
	
	<!-- Le javascript
	================================================== -->
	<!-- Placed at the end of the document so the pages load faster -->
	<script src="../assets/js/jquery.js"></script>
	<script src="../assets/js/bootstrap-transition.js"></script>
	<script src="../assets/js/bootstrap-alert.js"></script>
	<script src="../assets/js/bootstrap-modal.js"></script>
	<script src="../assets/js/bootstrap-dropdown.js"></script>
	<script src="../assets/js/bootstrap-scrollspy.js"></script>
	<script src="../assets/js/bootstrap-tab.js"></script>
	<script src="../assets/js/bootstrap-tooltip.js"></script>
	<script src="../assets/js/bootstrap-popover.js"></script>
	<script src="../assets/js/bootstrap-button.js"></script>
	<script src="../assets/js/bootstrap-collapse.js"></script>
	<script src="../assets/js/bootstrap-carousel.js"></script>
	<script src="../assets/js/bootstrap-typeahead.js"></script>
		

  </body>
</html>
